import Quagga from 'quagga';
class Scanner {
	constructor(ele, base64Img) {
		this.base64Img = base64Img;
		this.ele = ele;
	}

	// 扫描二维码
	scannerParseImg(onSuccess, onFailed) {
		let success = res => {
			if (res) {
				onSuccess(res.data);
			}
		};
		let error = err => {
			onFailed(err);
		};
		const QrCode = new QrCodeRecognition({ success, error });
		QrCode.upload(this.base64Img);
	}

	// 扫描条形码
	decodeScaneer(onSuccess, onFailed) {
		const config = {
			inputStream: {
				size: 800,
				singleChannel: false
			},
			locator: {
				patchSize: 'medium',
				halfSample: true
			},
			decoder: {
				readers: [
					{
						format: 'code_128_reader',
						config: {}
					},
					'ean_reader',
					'ean_8_reader',
					'code_39_reader',
					'code_39_vin_reader',
					'codabar_reader',
					'upc_reader',
					'upc_e_reader'
				]
			},
			locate: true,
			src: this.base64Img
		};
		console.log(Quagga);
		Quagga.decodeSingle(config, function(result) {
			if (!result || !result.codeResult || !result.codeResult.code) {
				let error = {};
				error.message = '扫码失败';
				error.code = 400;
				onFailed(error);
			} else {
				onSuccess(result.codeResult.code);
			}
		});
	}

	dataURLtoFile(dataurl, filename) {
		var arr = dataurl.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new File([u8arr], filename, { type: mime });
	}
}

export default Scanner;
